import arcpy

# 获取当前工程
aprx = arcpy.mp.ArcGISProject("CURRENT")

# 获取活动的地图或场景
active_map_or_scene = aprx.activeMap
# 查找对应名称的图层
target_layer_name = "梅川镇振兴社区_拉白膜"

target_layer = None
for lyr in active_map_or_scene.listLayers():
    if lyr.name == target_layer_name:
        target_layer = lyr
        break

if target_layer:
    fields_to_keep = ["FID", "Shape", "建筑顶", "建筑底", "建筑层", "uuid", "结构", "建筑高", "面积", "x", "y"]

    # 获取所有字段，并过滤出不需要保留的字段
    all_fields = [field.name for field in arcpy.ListFields(target_layer)]
    fields_to_delete = [field for field in all_fields if field not in fields_to_keep]

    if fields_to_delete:
        try:
            # 删除不需要保留的字段
            arcpy.management.DeleteField(target_layer, fields_to_delete)
            print(f"已成功删除字段: {', '.join(fields_to_delete)}")
        except arcpy.ExecuteError as e:
            print(f"发生错误: {e}")
    else:
        print("没有需要删除的字段")
else:
    print("图层未找到。")